package com.stu.manager.scoreinfo.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.manager.config.Result;
import com.stu.manager.course.entity.SysCourse;
import com.stu.manager.course.mapper.SysCourseMapper;
import com.stu.manager.personnel.entity.SysStudent;
import com.stu.manager.personnel.mapper.SysStudentMapper;
import com.stu.manager.scoreinfo.entity.SysScore;
import com.stu.manager.scoreinfo.entity.dto.ScoreInfoDto;
import com.stu.manager.scoreinfo.entity.vo.CourseVo;
import com.stu.manager.scoreinfo.mapper.SysScoreMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-02-16
 */
@Service
public class SysScoreServiceImpl extends ServiceImpl<SysScoreMapper, SysScore>{

    @Resource
    private SysCourseMapper courseMapper;

    @Resource
    private SysStudentMapper sysStudentMapper;

   /* public IPage<SysStudent> pageScore(Page<SysStudent> pageScore, Integer classGrade,String courseName,String jobNum) {
        QueryWrapper<SysCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("course_name",courseName).eq("job_num",jobNum);
        SysCourse sysCourse = courseMapper.selectOne(wrapper);
        String professionalName = sysCourse.getProfessionalName();

        QueryWrapper<SysStudent> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("professional_name",professionalName).eq("hiredate",classGrade);
        IPage<SysStudent> sysStudentIPage = sysStudentMapper.selectPage(pageScore, wrapper1);

        return sysStudentIPage;
    }*/

    //获取老师的所有年级所有课程
    public HashMap<String, List> getTeacherCourse(String jobNum) {
        QueryWrapper<SysCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("job_num",jobNum);
        List<SysCourse> sysCourses = courseMapper.selectList(wrapper);

        List<String> courseNames = sysCourses.stream().map(SysCourse::getCourseName).distinct().collect(Collectors.toList());
        List<Integer> grades = sysCourses.stream().map(SysCourse::getClassGrade).distinct().collect(Collectors.toList());
        HashMap<String, List> map = new HashMap<>();
        map.put("courseNames",courseNames);
        map.put("grades",grades);

        return map;
    }

    //成绩录入查询所有专业下学生
    public Result pageStudent(Page<SysStudent> pageStudent, Integer classGrade, String courseName, String jobNum) {

        QueryWrapper<SysCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("course_name",courseName).eq("job_num",jobNum).eq("class_grade",classGrade);

        Integer count = courseMapper.selectCount(wrapper);
        if(count == 0){
            return Result.ok().message("当前无此课程！");
        }

        SysCourse sysCourse = courseMapper.selectOne(wrapper);
        String professionalName = sysCourse.getProfessionalName();

        QueryWrapper<SysStudent> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("professional_name",professionalName).eq("hiredate",classGrade);
        IPage<SysStudent> sysStudentIPage = sysStudentMapper.selectPage(pageStudent, wrapper1);

        List<SysStudent> records = sysStudentIPage.getRecords();
        long total = sysStudentIPage.getTotal();

        return Result.ok().data("total", total).data("records", records);

    }

    //查询学生是否成绩录入
    public Result getScoreInfo(ScoreInfoDto scoreInfoDto) {
        Integer classGrade = scoreInfoDto.getClassGrade();
        String courseName = scoreInfoDto.getCourseName();
        Long stuNumber = scoreInfoDto.getStuNumber();

        QueryWrapper<SysScore> wrapper = new QueryWrapper<>();
        wrapper.eq("class_grade",classGrade).eq("course_name",courseName).eq("stu_number",stuNumber);
        Integer count = baseMapper.selectCount(wrapper);
        if (count>0){
            SysScore sysScore = baseMapper.selectOne(wrapper);
            return Result.ok().data("sysScore",sysScore);
        }else {
            return Result.ok().data("sysScore","");
        }

    }

    //输入成绩
    public Result inputScore(SysScore sysScore) {
        String id = sysScore.getId();
        if(StringUtils.isEmpty(id)){//第一次加
            //平时成绩30%，期末成绩70%
            Double normalScore = sysScore.getNormalScore() * 0.3;
            Double endScore = sysScore.getEndScore() * 0.7;

            sysScore.setTotalScore(normalScore+endScore);

            int insert = baseMapper.insert(sysScore);
            if(insert>0){
                return Result.ok().message("录入成功！");
            }else {
                return Result.error().message("录入失败！");
            }
        }else{//修改成绩
            //平时成绩30%，期末成绩70%
            Double normalScore = sysScore.getNormalScore() * 0.3;
            Double endScore = sysScore.getEndScore() * 0.7;

            sysScore.setTotalScore(normalScore+endScore);

            int insert = baseMapper.updateById(sysScore);
            if(insert>0){
                return Result.ok().message("录入成功！");
            }else {
                return Result.error().message("录入失败！");
            }
        }
    }



    public void importStudentToScore(CourseVo courseVo,String jobNum) {
        String courseName = courseVo.getCourseName();
        Integer classGrade = courseVo.getClassGrade();

        /*QueryWrapper<SysScore> wrapperScore = new QueryWrapper<>();
        wrapperScore.eq("course_name",courseName).eq("class_grade",classGrade);
        Integer count = baseMapper.selectCount(wrapperScore);
        if(count == 0){*/
            QueryWrapper<SysCourse> wrapperCourse = new QueryWrapper<>();
            wrapperCourse.eq("course_name",courseName).eq("class_grade",classGrade).eq("job_num",jobNum);
        Integer count1 = courseMapper.selectCount(wrapperCourse);
        if(count1 == 0){
            return;
        }
        SysCourse sysCourse = courseMapper.selectOne(wrapperCourse);
            String professionalName = sysCourse.getProfessionalName();

            //把专业年级下所有学生信息查出来
            QueryWrapper<SysStudent> wrapperStudent = new QueryWrapper<>();
            wrapperStudent.eq("professional_name",professionalName).eq("hiredate",classGrade);
            List<SysStudent> sysStudents = sysStudentMapper.selectList(wrapperStudent);
            for (SysStudent sysStudent : sysStudents) {
                //先判断这个学生是否已经加入到成绩表
                Long stuNumber = sysStudent.getStuNumber();
                QueryWrapper<SysScore> wrapper = new QueryWrapper<>();
                wrapper.eq("stu_number",stuNumber).eq("course_name",courseName);
                Integer count = baseMapper.selectCount(wrapper);
                if(count==0){//没加入成绩表就加
                    SysScore sysScore = new SysScore();
                    sysScore.setStuNumber(stuNumber);
                    sysScore.setClassGrade(classGrade);
                    sysScore.setJobNum(Long.parseLong(jobNum));
                    sysScore.setStuName(sysStudent.getStuName());
                    sysScore.setCourseName(courseName);
                    sysScore.setNormalScore(0.0);
                    sysScore.setEndScore(0.0);
                    sysScore.setTotalScore(0.0);
                    baseMapper.insert(sysScore);
                }

            }
//        }
    }

    //分页获取成绩信息
    public Result pageScore(Page<SysScore> pageScore, Integer classGrade, String courseName) {
        QueryWrapper<SysScore> wrapper = new QueryWrapper<>();
        wrapper.eq("class_grade",classGrade).eq("course_name",courseName);
        IPage<SysScore> sysScoreIPage = baseMapper.selectPage(pageScore, wrapper);
        List<SysScore> records = sysScoreIPage.getRecords();
        long total = sysScoreIPage.getTotal();

        return Result.ok().data("total", total).data("records", records);
    }


    //生成课程学生的几个与不及格比例图表
    public Result createCharts(Integer classGrade, String courseName,String jobNum) {
        QueryWrapper<SysScore> wrapper = new QueryWrapper<>();
        //成绩大于等于60
        wrapper.eq("job_num",jobNum).eq("class_grade",classGrade).eq("course_name",courseName).ge("total_score",60);
        Integer countA = baseMapper.selectCount(wrapper);

        //成绩小于60的
        QueryWrapper<SysScore> wrapperB = new QueryWrapper<>();
        wrapperB.eq("job_num",jobNum).eq("class_grade",classGrade).eq("course_name",courseName).lt("total_score",60);
        Integer countB = baseMapper.selectCount(wrapperB);

        JSONObject jsonObject = new JSONObject();
        jsonObject.set("name","及格人数");
        jsonObject.set("value",countA);

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.set("name","不及格人数");
        jsonObject1.set("value",countB);

        List<JSONObject> list = new ArrayList<>();
        list.add(jsonObject);
        list.add(jsonObject1);

        return Result.ok().data("stadata",list);
    }

    //生成课程学生的成绩折线图
    public Result createLineCharts(Integer classGrade, String courseName, String jobNum) {
        QueryWrapper<SysScore> wrapper = new QueryWrapper<>();
        wrapper.eq("job_num",jobNum).eq("class_grade",classGrade).eq("course_name",courseName);
        List<SysScore> sysScores = baseMapper.selectList(wrapper);
        List<String> stuNames = new ArrayList<>();
        List<Double> scores = new ArrayList<>();

        for (SysScore sysScore : sysScores) {
            Double totalScore = sysScore.getTotalScore();
            String stuName = sysScore.getStuName();
            stuNames.add(stuName);
            scores.add(totalScore);
        }

        return Result.ok().data("stuNames",stuNames).data("scores",scores);
    }
}
